$(() => {
  let $width = $('#width'),
      $height = $('#height'),
      $btnCal = $('#calc'),
      $perimeter = $('#perimeter'),
      $area = $('#area'),
      $widthValidate = $('#width-validate'),
      $heightValidate = $('#height-validate')
      isPassValidate = false;

  $width.focusout(() => {
    let result = validate($width,$widthValidate);
    isPassValidate = result.isOK;
    if(!result.isOK){
      $widthValidate.html(result.reason);
      $width.select();
    }else{
      $widthValidate.html('');
    }
  })
  $width.keypress($width => {
    isKey($width.key,$width.target.value,$width.target.selectionStart) || $width.preventDefault();
  })

  $height.focusout(() => {
    let result = validate($height,$heightValidate);
    isPassValidate = result.isOK;
    if(!result.isOK){
      $heightValidate.html(result.reason);
      $height.select();
    }else{
      $heightValidate.html('');
    }
  })

  $height.keypress($height => {
    isKey($height.key,$height.target.value,$height.target.selectionStart) || $height.preventDefault();
  })
  
  /* calc button click */
  $btnCal.click(() => {
    if(!isPassValidate) return;
    let w = Number($width.val());
    let h = Number($height.val());
    let p = (w+h)*2,
        a = w * h;
    function l1(x,n){
      return Math.round(x * Math.pow(10,n)) / Math.pow(10,n);
    }
    let m1,m2;
    try{
      m1 = w.toString().split('.')[1].length;
    }catch(e){
      m1 = 0;
    }
    try{
      m2 = h.toString().split('.')[1].length;
    }catch(e){
      m2 = 0;
    }
    //output
    $perimeter.val(l1(p,Math.max(m1,m2)));
    $area.val(l1(a,m1+m2));
  });
});


function validate(input,output){
  let result = {
    isOK: false,
    reason: ''
  }
  if(input.val() === ''){
    result.reason = '该字段不能为空';
    output.html(result.reason);
    return result;
  } 
  let val = Number(input.val());
  if(isNaN(val)){
    result.reason = '该字段应该为数值';
    return result;
  }
  if(val < 0){
    result.reason = '该数值不能小于零';
    return result;
  }
  result.isOK = true;
  return result;
}

function isKey(key,content,pos) { 
  if(/[abcdf-zABCDF-Z`~!@#$%^&*()=+[\]{}|;:'",<>/?\\]/.test(key)){
    return false;
  }

  if(key === '.') {
    if(pos === 0) return false;
    if(content.indexOf('.') !== -1) return false;
    if(pos > 0 && /[-eE]/.test(content.slice(0,pos))) return false;
  }

  if(key === 'e' || key === 'E') {
    if(pos === 0) return false;
    if(content.indexOf('e') !== -1 || content.indexOf('E') !== -1) return false;
    if(pos > 0 && /[-.]/.test(content.slice(pos-1,pos))) return false;
  }

  if(key === '-') {
    if(pos === 0) return false;
    if(pos > 0 && /[0-9.]/.test(content.slice(pos-1,pos))) return false;
    if(pos > 0 && content.indexOf('-') !== -1) return false;
  }
  return true;
}
